var distr_managebill = require('../model/distribution_manage')
var acttoolv2 = require('../../../xc/sys/toolv2')
Page({
  mixins: [require('../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    pagetitle: "",
    loading: true,
    distrinfo: {
      brokerage: "0",
      totalbrokerage: "0"
    },
    memberinfo: {},
    billnums: {
      all: 0,
      notreceived: 0,
      nowriteoff: 0,
      finish: 0
    },
    noticelist: [],
    noticeshow: false,
    popnotice: {
      name: "",
      contant: ""
    }
  },
  //申请股东
  applygudo() {
    console.log(this.data.distrinfo)
    if (this.data.distrinfo.is_shareholder == 2) {
      wx.showToast({
        icon: 'none',
        title: '申请中',
      })
    } else {
      this.selectComponent("#popup").init();
    }
  },
  //同意股东
  agree(e) {
    console.log(e)
    this.gudongapply()
  },
  gudongapply() {
    var that = this;
    distr_managebill.gudongapply().then(function (rst) {
      console.log("rst")
      console.log(rst)

      if (rst["status"] == 1) {
        that.setData({
          'distrinfo.is_shareholder': 2
        })
      }



    })
  },
  showqr: function () {
    var widgetsshare = this.selectComponent("#widgetsshare");
    widgetsshare.showSharefunc()
  },
  refreshmember() {
    var that = this
    distr_managebill.refreshmember().then(function (rst) {
      if (rst["status"] == 1) {
        const app = getApp()

        app.globalData.member = rst["obj"];
        var memberinfo = rst["obj"]['memberinfo']
        that.setData({
          memberinfo
        })

        if (memberinfo["is_distribution"] != 1) {
          wx.redirectTo({
            url: '../info/apply',
          })
        } else {
          that.centerinfo()
        }
      }
    })

  },
  xcloaddata: function (options, config) {
    this.setconfig(config)

  },
  setconfig(config) {
    const app = getApp()

    var basicurl = app.globalData.basicurl
    var update = {};
    var cpsstatus = -1;
    if (config["smapiconfig"] && config["smapiconfig"]['basic']['status'] == 1) {
      cpsstatus = 1;
    }
    if (config["jtklmapi"] && config["jtklmapi"]['status'] == 1) {
      cpsstatus = 1;
    }

    update['cpsstatus'] = cpsstatus

    var disconfig = "";
    if (config.distribution) {

      disconfig = config.distribution
    } else {
      disconfig = {
        distext: {
          center: {
            center: "分销中心",
            accumulatecommission: "累计佣金",
            widthdrawcommission: "已提现佣金",
            withdrawablecommission: "可提现佣金",
            widthdrawrecord: "提现记录",
            withdrawal: "提现",
            code: "邀请码",
            grade: "默认等级",
            qrcode: "推广二维码",
            gdservice: "股东服务",
            disservice: "分销服务",
            allbonus: "累计分红",
            allshares: "总股份",
            myshares: "我的股份",
            sharesrate: "股份占比",
          }
        }
      }
    }
    // delete disconfig.distext.disnav
    // delete disconfig.distext.gdnav
    console.log("disconfig")
    console.log(disconfig)

    if (!disconfig.distext['disnav']) {
      disconfig.distext['disnav'] = {
        imgslist: [{
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/tixian.png",
            name: "提现记录",
            status: "1",
            url: "/xc_lshop/distr/manage/center?op=cashoutrecord",
          },
          {
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/order.png",
            name: "分销订单",
            status: "1",
            url: "/xc_lshop/distr/manage/distrorder",
          },
          {
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/team.png",
            name: "我的团队",
            status: "1",
            url: "/xc_lshop/distr/manage/myteam",
          },
          {
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/cps.png",
            name: "CPS分销明细",
            status: "1",
            url: "/xc_lshop/distr/manage/smorder",
          },
        ]
      }
    }
    if (!disconfig.distext['gdnav']) {
      disconfig.distext['gdnav'] = {
        imgslist: [{
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/TouristSource.png",
            name: "我的客源",
            status: "1",
            url: "/xc_lshop/distr/shareholder/source",
          },
          {
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/equity.png",
            name: "股本记录",
            status: "1",
            url: "/xc_lshop/distr/shareholder/equity",
          },
          {
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/bonus.png",
            name: "分红记录",
            status: "1",
            url: "/xc_lshop/distr/shareholder/bonus",
          },
          {
            cid: "1",
            imgurl: basicurl + "/eq/images/discenter/Statistics.png",
            name: "分红统计",
            status: "1",
            url: "/xc_lshop/distr/shareholder/statistics",
          },
        ]
      }
    }

    update['disconfig'] = disconfig

    this.setData(update)
  },
  op(e) {
    // console.log("e")
    var item = e.currentTarget.dataset.item;
    let op = this.getQueryVariable(item.url, 'op')
    if (op) {
      if (op == 'cashoutrecord') {
        this.cashoutrecord()
      }
    } else {
      wx.navigateTo({
        url: item.url,
      })
    }
    // console.log(data)

    // console.log(e)
  },
  getQueryVariable(url, variable) {
    var all = url.split("?"); // 根据“?”切割数组，截取“?”之后的字符串
    if (all[1]) {
      var query = url.split("?")[1]; // 根据“?”切割数组，截取“?”之后的字符串
      // ['https://qq.com','appid=1234567890&name=Zdf']
      var vars = query.split("&"); // 根据“&”切割成数组
      // ['appid=1234567890','name=Zdf']
      for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        // ['appid','1234567890']
        if (pair[0] == variable) return pair[1]; // 没有花括号默认执行第一个js语句
      }
      return (false);

    } else {
      return (false);

    }

  },
  //   convertUrlQuery($query)
  // {
  //     var queryParts = explode('&', $query);
  //     var params = array();
  //     foreach (queryParts as param) {
  //         $item = explode('=', $param);
  //         $params[$item[0]] = $item[1];
  //     }
  //     return $params;
  // },
  withdrawal: function () {
    var that = this
    if (this.data.distrinfo) {
      var cashoutcom = that.selectComponent("#cashoutcom");
      cashoutcom.showmodel('distr', this.data.distrinfo);
    } else {
      wx.showToast({
        title: '等待数据加载',
      })
    }
  },
  cashoutrecord: function (e) {
    var app = getApp();

    if (this.data.memberinfo) {
      var cashoutrecord = this.selectComponent("#cashoutrecord");
      cashoutrecord.showmodel('distr', this.data.memberinfo.id);
    }
  },
  aftercashout: function (e) {

    //提现之后更新
    var reslut = e.detail
    var app = getApp();
    this.setData({
      "distrinfo.brokerage": reslut['obj'].brokerage
    })
  },
  afterlogin: function (options, config, userinfo) {
    var that = this;


    //1.分销未开启 返回
    if (!config.distribution || config.distribution.status != 1) {
      this.pageback()
      return;
    }

    this.data.homeurl = config.basic.homeurl
    var app = getApp()
    //2.需要注册后  

    app.xc_sys_config.authop.oppower("login").then(function (res) {
      if (res["status"] == 1) {
        var memberinfo = res["obj"]["memberinfo"]
        that.setData({
          memberinfo
        })

        if (memberinfo["is_distribution"] != 1) {
          that.refreshmember()
        } else {
          that.centerinfo()
        }
      } else {
        that.pageback()
      }

      // that.setData({ "member": app.globalData.member,configclub:config.club })    
    })


    //cashoutcom
  },
  centerinfo() {
    var that = this


    this.getnotice()


    distr_managebill.centerinfo().then(function (rst) {
      console.log("rst")
      console.log(rst)
      console.log(that.data.memberinfo)

      if (rst["status"] == 1) {
        var formdata = {};
        if (rst["obj"]["withdrawinfo"]) {
          formdata = rst["obj"]["withdrawinfo"]
        } else {
          if (rst["obj"]['phone']) {
            formdata['phone'] = rst["obj"]['phone'];
          }
          if (rst["obj"]['name']) {
            formdata['name'] = rst["obj"]['name'];
          }
          if (!formdata['phone']) {
            formdata['phone'] = that.data.memberinfo.phone
          }
          if (!formdata['name']) {
            formdata['name'] = that.data.memberinfo.name
          }
        }
        console.log(formdata)
        that.setData({
          formdata,
          distrinfo: rst["obj"]
        })

        // console.log(that.data.disconfig.distext.disnav.imgslist)
        that.changeimg(rst["obj"]);
        that.loadstatus(false)
      }



    })


  },
  changeimg(distrinfo) {
    var imgs = this.data.disconfig.distext.disnav.imgslist;
    var imgslist = []
    for (var i in imgs) {
      if (imgs[i]['cid'] == 1) {
        if (imgs[i]['url']) {
          if (imgs[i]['url'] == '/xc_lshop/distr/manage/orderlist/areaorder') { //区域佣金
            if (distrinfo.arealist) {
              imgslist.push(imgs[i])
            }
          } else if (imgs[i]['url'] == '/xc_lshop/distr/manage/leader/index') { //团队长
            if (distrinfo.isleader == 1) {
              imgslist.push(imgs[i])

            }
          }else if (imgs[i]['url'] == '/xc_lshop/distr/manage/leader/statistics') { //团队长统计
            if (distrinfo.isleader == 1) {
              imgslist.push(imgs[i])
            }
          } else {
            imgslist.push(imgs[i])
          }

        }
      } else {
        imgslist.push(imgs[i])
      }
    }

    this.setData({
      'disconfig.distext.disnav.imgslist': imgslist
    })
  },
  onNoticeClose() {
    var popnotice = {
      name: "",
      contant: ""
    }
    this.setData({
      popnotice: popnotice,
      noticeshow: false
    })
  },
  shownoticedetail(e) {

    var dataset = e.currentTarget.dataset;
    var popnotice = {
      name: dataset.item.name,
      contant: dataset.item.contents,
    }
    this.setData({
      noticeshow: true,
      popnotice: popnotice

    })
  },
  //分销通知列表
  getnotice() {
    var that = this
    distr_managebill.getnotice().then(function (rst) {
      if (rst['status'] == 1) {
        that.setData({
          noticelist: rst['obj']
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})